<template>
  <CommonLayout
    pageTitle="用户管理"
    sidebarTitle="用户筛选"
    :loading="loading"
    :isEmpty="users.length === 0 && !loading"
    emptyText="暂无普通用户数据"
  >
    <!-- 侧边栏筛选区 -->
    <template #sidebar>
      <form class="filter-form" @submit.prevent="handleFilter">
        <div class="filter-item">
          <label>关键字搜索</label>
          <input
            v-model="filterForm.keyword"
            placeholder="用户名/邮箱/手机号"
            class="filter-input"
          />
        </div>

        <div class="filter-item">
          <label>创建时间范围</label>
          <div class="date-range">
            <input
              v-model="filterForm.startDate"
              type="date"
              class="date-input"
            />
            <span class="range-separator">-</span>
            <input
              v-model="filterForm.endDate"
              type="date"
              class="date-input"
            />
          </div>
        </div>

        <div class="filter-item">
          <label>用户状态</label>
          <select v-model="filterForm.status" class="filter-select">
            <option value="">全部状态</option>
            <option value="active">正常</option>
            <option value="inactive">禁用</option>
          </select>
        </div>

        <!-- 新增时间排序选项 -->
        <div class="filter-item">
          <label>时间排序</label>
          <select v-model="filterForm.sortBy" class="filter-select">
            <option value="">默认排序</option>
            <option value="created_at_asc">创建时间升序</option>
            <option value="created_at_desc">创建时间降序</option>
          </select>
        </div>

        <button type="submit" class="filter-btn">应用筛选</button>
        <button
          type="button"
          class="reset-btn"
          @click="resetFilter"
        >
          重置筛选
        </button>
      </form>
    </template>

    <!-- 主内容区 -->
    <template #content>
      <div class="product-table-container">
        <table class="product-table">
          <thead>
            <tr>
              <th>用户名</th>
              <th>邮箱</th>
              <th>手机号</th>
              <th>创建时间</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in users" :key="user.id" class="product-row">
              <td>{{ user.username }}</td>
              <td>{{ user.email }}</td>
              <td>{{ user.phone || '-' }}</td>
              <td>{{ formatDate(user.created_at) }}</td>
              <td>
                <span :class="['status-tag', user.status === 1 ? 'status-active' : 'status-inactive']">
                  {{ user.status === 1 ? '正常' : '禁用' }}
                </span>
              </td>
              <td class="action-buttons">
                <button
                  class="btn-common btn-编辑"
                  @click="handleEdit(user.user_id)"
                >
                  编辑
                </button>
                <button
                  class="btn-common btn-删除"
                  @click="handleDelete(user.user_id)"
                >
                  删除
                </button>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <div class="pagination-info">
            共 {{totalPages}} 页，当前第 {{currentPage}} 页，每页 {{pageSize}} 条
          </div>
          <div class="pagination-buttons">
            <button @click="prevPage" :disabled="currentPage === 1" class="pagination-btn">上一页</button>
            <button
              v-for="page in pageRange"
              :key="page"
              @click="goToPage(page)"
              :class="{ 'pagination-btn': true, 'active': page === currentPage }"
            >
              {{ page }}
            </button>
            <button @click="nextPage" :disabled="currentPage === totalPages" class="pagination-btn">下一页</button>
          </div>
        </div>
      </div>
    </template>
  </CommonLayout>

  <!-- 新增编辑用户模态框 -->
  <div v-if="isEditDialogVisible" class="edit-dialog-overlay">
    <div class="edit-dialog">
      <h3 class="dialog-title">编辑用户</h3>
      <form class="edit-form" @submit.prevent="submitEdit">
        <div class="form-item">
          <label>用户名</label>
          <input v-model="editUser.username" readonly class="form-input" />
        </div>
        <div class="form-item">
          <label>邮箱</label>
          <input v-model="editUser.email" type="email" class="form-input" />
        </div>
        <div class="form-item">
          <label>手机号</label>
          <input v-model="editUser.phone" class="form-input" />
        </div>
        <div class="form-item">
          <label>状态</label>
          <select v-model="editUser.status" class="form-select">
            <option value="1">正常</option>
            <option value="0">禁用</option>
          </select>
        </div>
        <div class="dialog-actions">
          <button type="button" class="btn-cancel" @click="isEditDialogVisible = false">取消</button>
          <button type="submit" class="btn-confirm">确认</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue';
import axios from 'axios';
import CommonLayout from '../components/CommonLayout.vue';
import { formatDate } from '../utils/date-utils.ts';

// 定义用户接口类型
interface User {
  user_id: number;
  username: string;
  email: string;
  phone?: string;
  status: number;
  created_at: string;
}

// 编辑相关变量
const isEditDialogVisible = ref<boolean>(false);
const editUser = ref<User>({ 
  user_id: 0, 
  username: '', 
  email: '', 
  status: 1, 
  created_at: '' 
});

// 分页相关状态
const currentPage = ref(1);
const totalPages = ref(1);
const pageSize = ref(10); // 每页显示10条数据

/**
 * 用户管理页面组件
 * 功能：展示普通用户列表，提供筛选、编辑和删除功能
 */

// 筛选表单数据
const filterForm = reactive<{
  keyword: string;
  startDate: string;
  endDate: string;
  status: string;
  sortBy: string; // 新增排序字段
}>({
  keyword: '',
  startDate: '',
  endDate: '',
  status: '',
  sortBy: ''
});

// 状态管理
const users = ref<any[]>([]);
const loading = ref<boolean>(false);

/**
 * 获取页码范围，用于显示分页按钮
 * @returns 页码数组
 */
const pageRange = computed(() => {
  const range = [];
  const maxVisiblePages = 5; // 最多显示5个页码按钮
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2));
  let endPage = startPage + maxVisiblePages - 1;

  if (endPage > totalPages.value) {
    endPage = totalPages.value;
    startPage = Math.max(1, endPage - maxVisiblePages + 1);
  }

  for (let i = startPage; i <= endPage; i++) {
    range.push(i);
  }

  return range;
});

/**
 * 跳转到上一页
 */
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchUsers();
  }
};

/**
 * 跳转到下一页
 */
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    fetchUsers();
  }
};

/**
 * 跳转到指定页码
 * @param page 目标页码
 */
const goToPage = (page: number) => {
  if (page !== currentPage.value && page >= 1 && page <= totalPages.value) {
    currentPage.value = page;
    fetchUsers();
  }
};

/**
 * 获取用户列表数据
 * @param filters 筛选条件
 */
const fetchUsers = async (filters?: Record<string, any>) => {
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    const params = {
      ...filters,
      role: 'user', // 仅获取普通用户
      page: currentPage.value,
      pageSize: pageSize.value
    };

    // 前端日志：记录请求参数
    console.log(`[${new Date().toISOString()}] [INFO] [用户管理] 请求参数: ${JSON.stringify(params)}`);

    const response = await axios.get('/api/admin/users', {
      headers: { Authorization: `Bearer ${token}` },
      params,
    });

    // 前端日志：记录响应结果
    console.log(`[${new Date().toISOString()}] [INFO] [用户管理] 响应结果: ${JSON.stringify(response.data)}`);

    users.value = response.data.users || [];
    // 更新分页信息
    totalPages.value = response.data.pagination?.totalPages || 1;
    console.log(`[${new Date().toISOString()}] [DEBUG] [用户管理] 分页信息: totalPages=${totalPages.value}, currentPage=${currentPage.value}, pageRange=${JSON.stringify(pageRange.value)}`);
  } catch (error: any) {
    console.error(`[${new Date().toISOString()}] [ERROR] [用户管理] 获取用户列表失败:`, error);
    alert(`获取用户列表失败: ${error.message}`);
    users.value = [];
    totalPages.value = 1;
  } finally {
    loading.value = false;
  }
};

/**
 * 处理筛选提交
 */
const handleFilter = () => {
  // 构建筛选参数
  const filters: Record<string, any> = {};
  if (filterForm.keyword) filters.keyword = filterForm.keyword;
  if (filterForm.startDate) filters.startDate = filterForm.startDate;
  if (filterForm.endDate) filters.endDate = filterForm.endDate;
  if (filterForm.status) filters.status = filterForm.status;
  if (filterForm.sortBy) filters.sortBy = filterForm.sortBy; // 添加排序参数

  // 重置到第一页
  currentPage.value = 1;
  fetchUsers(filters);
};

/**
 * 重置筛选条件
 */
const resetFilter = () => {
  filterForm.keyword = '';
  filterForm.startDate = '';
  filterForm.endDate = '';
  filterForm.status = '';
  filterForm.sortBy = '';
  // 重置到第一页
  currentPage.value = 1;
  fetchUsers();
};

/**
 * 处理用户编辑
 * @param userId 用户ID
 */
const handleEdit = async (userId: number) => {
  try {
    const token = localStorage.getItem('token');
    const response = await axios.get(`/api/admin/users/${userId}`, {
      headers: { Authorization: `Bearer ${token}` },
    });
    editUser.value = response.data.user;
    isEditDialogVisible.value = true;
  } catch (error: any) {
    console.error(`[${new Date().toISOString()}] [ERROR] [用户管理] 获取用户详情失败:`, error);
    alert(`获取用户详情失败: ${error.message}`);
  }
};

/**
 * 提交用户编辑
 */
const submitEdit = async () => {
  try {
    const token = localStorage.getItem('token');
    await axios.put(`/api/admin/users/${editUser.value.user_id}`, editUser.value, {
      headers: { Authorization: `Bearer ${token}` },
    });
    alert('编辑成功');
    isEditDialogVisible.value = false;
    fetchUsers(); // 重新获取用户列表
  } catch (error: any) {
    console.error(`[${new Date().toISOString()}] [ERROR] [用户管理] 编辑用户失败:`, error);
    alert(`编辑用户失败: ${error.message}`);
  }
};

/**
 * 处理用户删除
 * @param userId 用户ID
 */
const handleDelete = async (userId: number) => {
  if (!confirm('确定要删除该用户吗？')) return;

  try {
    const token = localStorage.getItem('token');
    await axios.delete(`/api/admin/users/${userId}`, {
      headers: { Authorization: `Bearer ${token}` },
    });
    alert('删除成功');
    // 重新获取用户列表
    fetchUsers();
  } catch (error: any) {
    console.error(`[${new Date().toISOString()}] [ERROR] [用户管理] 删除用户失败:`, error);
    alert(`删除用户失败: ${error.message}`);
  }
};

// 页面加载时获取用户列表
onMounted(() => {
  console.log(`[${new Date().toISOString()}] [INFO] [用户管理] 组件已挂载，开始获取数据`);
  fetchUsers();
});
</script>

<style scoped>
/* 复用商品管理页面的样式，根据需要调整 */
.filter-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-input,
.filter-select,
.date-input {
  width: 100%;
  padding: 8px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
}

.date-range {
  display: flex;
  gap: 8px;
  align-items: center;
}

.date-input {
  flex: 1;
}

.range-separator {
  color: #64748b;
}

.filter-btn {
  padding: 8px;
  background: #2563eb;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.reset-btn {
  padding: 8px;
  background: #f1f5f9;
  color: #334155;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.product-table-container {
  overflow-x: auto;
}

.product-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 600px;
}

.product-table th,
.product-table td {
  padding: 12px 16px;
  text-align: left;
  vertical-align: middle;
}

.product-table th {
  background-color: #f8fafc;
  font-weight: 600;
  color: #334155;
}

.product-row:hover {
  background-color: #f8fafc;
}

/* 状态标签样式 */
.status-tag {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
}

.status-active {
  background-color: #dcfce7;
  color: #166534;
}

.status-inactive {
  background-color: #fee2e2;
  color: #b91c1c;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

/* 操作按钮公共样式 */
.btn-common {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
}

/* 编辑按钮样式 */
.btn-编辑 {
  background-color: #e0f2fe;
  color: #0369a1;
}

/* 删除按钮样式 */
.btn-删除 {
  background-color: #fee2e2;
  color: #b91c1c;
}

/* 禁用状态样式 */
.btn-编辑:disabled,
.btn-删除:disabled {
  background-color: #f1f5f9;
  color: #94a3b8;
  cursor: not-allowed;
}

/* 编辑模态框样式 */
.edit-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.edit-dialog {
  background-color: white;
  border-radius: 8px;
  width: 400px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.dialog-title {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
}

.edit-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-input,
.form-select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
}

.form-input:read-only {
  background-color: #f8fafc;
  cursor: not-allowed;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 16px;
}

.btn-cancel,
.btn-confirm {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  border: none;
}

.btn-cancel {
  background-color: #f1f5f9;
  color: #334155;
}

.btn-confirm {
  background-color: #2563eb;
  color: white;
}

/* 分页按钮样式 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 10px;
}

.pagination-info {
  color: #64748b;
  font-size: 14px;
}

.pagination-buttons {
  display: flex;
  gap: 8px;
}

.pagination-btn {
  padding: 6px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  background-color: white;
  color: #334155;
  cursor: pointer;
  font-size: 14px;
}

.pagination-btn:hover {
  background-color: #f8fafc;
}

.pagination-btn:active {
  background-color: #e2e8f0;
}

.pagination-btn:disabled {
  background-color: #f1f5f9;
  color: #94a3b8;
  cursor: not-allowed;
}

.pagination-btn.active {
  background-color: #2563eb;
  color: white;
  border-color: #2563eb;
}
</style>